#!/bin/sh

# 错误检查
set -e


# 提取目录名中的项目名称
project=$(basename "${PWD}")

action=${1-deploy}
version=${2:-master}
rbranch=${3-master}
echo "${action}项目：${project},版本${version},发布分支${rbranch}"

# todo: 检查unzip是否安装

pull() {
    DOWNLOAD_URL="https://gitee.com/kelc/release/raw/master/${project}/${version}.zip"
    echo 下载配置文件:$DOWNLOAD_URL
    mkdir -p ./release
    wget -qO "./release/${version}.zip" "${DOWNLOAD_URL}"
    # unzip -o "${version}.zip"
}

deploy() {
    if [ -e "./release/${version}.zip" ]; then
        unzip -o "./release/${version}.zip"
    else
        pull
        unzip -o "./release/${version}.zip"
    fi

    if [ -e "install.sh" ]; then  # 如果存在install.sh,则执行install.sh
        echo 执行项目安装:bash install.sh
        bash install.sh -i -d
    else   # 如果不存在install.sh,则执行docker-compose
        echo docker部署启动应用
        docker-compose down --remove-orphans
        docker-compose pull
        docker-compose up -d
    fi
}

if [ "${action}" = "pull" ]; then
    pull
elif [ "${action}" = "deploy" ]; then
    deploy
else
    echo "action为[pull/deploy],${action}参数错误"
    exit
fi

echo done
